package cn.com.hhrcw.utils.resume;

import cn.com.hhrcw.area.service.ISysAreaService;
import cn.com.hhrcw.entity.*;
import cn.com.hhrcw.service.*;
import cn.com.hhrcw.utils.edu.EduLabelUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * <p>
 * 生成html  * 版的简历（2022年4月1日10:45:55 zhf 抽离出来，原来所在是ICvResumeService 代码 太长 ）
 * </p>
 *
 * @author jiangdong
 * @since 2020-10-29
 */

@Transactional(rollbackFor = Exception.class)
@Slf4j
@Component
public class ResumeHtmlUtil {

    @Autowired
    IPiInfoService piInfoService;

    @Autowired
    ICvResumeService cvResumeService;

    @Autowired
    private EduLabelUtil eduLabelUtil;

    @Autowired
    private ICvWorkIntentionService cvWorkIntentionService;

    @Autowired
    private ICvUserWorkInfoService cvUserWorkInfoService;

    @Autowired
    private ICvUserEduInfoService cvUserEduInfoService;

    @Autowired
    private ICvProjectInfoService cvProjectInfoService;

    @Autowired
    private ICvTrainService cvTrainService;

    @Autowired
    private ICvLanguageLevelService cvLanguageLevelService;

    @Autowired
    private ICvSkillsService cvSkillsService;

    @Autowired
    private ICvCertificateService cvCertificateService;

    @Autowired
    private TransNameUtil transNameUtil;

    @Autowired
    private IFileService fileService;

    @Autowired
    private ISysBaseAPI sysBaseAPI;

    @Autowired
    private IOpJobService opJobService;

    @Autowired
    private IOpDeliveryHistoryService opDeliveryHistoryService;

    @Autowired
    private ICvFamilyMemberService cvFamilyMemberService;

    @Autowired
    private ISysAreaService sysAreaService;

    public static final String FORMAT = "yyyy.MM";

    public String generateResumeHtml(String userId, Integer lanType, String jobId) {
        //实际仅生成html（pdf 需要插件，客户暂未购买）
        try {
            cvResumeService.getResumeInfo(userId, lanType, jobId);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        final String[] level = {"初中", "高中", "中专/中技", "大专", "本科", "硕士", "MBA/EMBA", "博士", "无"};
        final String[] sex = {"保密", "男", "女"};
        final String[] maritalStatus = {"未婚", "已婚已育", "已婚未育", "离异"};
        PiInfo info = piInfoService.lambdaQuery().eq(PiInfo::getDelFlag, false).eq(PiInfo::getUserId, userId).one();
        if (info.getJobTime() == null || info.getJobFlag() == 0) {
            info.setJobTime(cn.hutool.core.date.DateUtil.date());
        }
        CvResume cvResume = cvResumeService.lambdaQuery().eq(CvResume::getDelFlag, false).eq(CvResume::getUserId, userId).eq(CvResume::getLanType, lanType).eq(CvResume::getType, 0).one();
        String resumeHtmlName = StrUtil.format("{}_{}_{}.html", info.getName(), info.getPhone(), lanType == 0 ? "在线中文简历" : "在线英文简历");
        Dict dict = Dict.create();
        String[] liveCity = null;

        //2022年4月8日18:39:29 zhuf 添加
        dict.set("adv", cvResume.getAdvantage());
        dict.set("advantage", cvResume.getAdvantage());
        String majorWorkPerformance = cvResume.getMajorWorkPerformance();
        if(StrUtil.isBlank(majorWorkPerformance) || "无".equals(majorWorkPerformance.trim())){
            majorWorkPerformance = "/";
        }
        dict.set("majorWorkPerformance", majorWorkPerformance);

        if (StrUtil.isNotBlank(info.getLiveCity())) {
            liveCity = info.getLiveCity().split(",");
            dict.set("liveCity", transNameUtil.getTransName("sys_area", liveCity[liveCity.length - 1], "id", "name"));
        } else {
            dict.set("liveCity", "");
        }

        String[] home = null;
        try {
            // 2022年3月14日16:23:02 zhf 临时 调整
            home = info.getHomeTown().split(",");
            dict.set("home", transNameUtil.getTransName("sys_area", home[home.length - 1], "id", "name"));
        } catch (Exception e) {
            dict.set("home", "");
            log.warn("城市数据提前错误：", info.getLiveCity());

        }

        File photo = this.fileService.getById(info.getPhotoId());
        String photoUrl = photo != null ? photo.getUrl() : "";
        dict.set("name", info.getName())
            .set("age", info.getAge())
            .set("sex", info.getSex() == null ? "无" : sex[info.getSex()])
            .set("workExperience", info.getWorkYears())
            //2022年3月14日16:26:28 注释下述两行，上面已经调整 -解决部分信息填写不完全的错误
            .set("political", info.getPolitical())
            .set("phone", info.getPhone())
            .set("email", info.getEmail())
            .set("pic", photoUrl)
            .set("majorResearchDirection", cvResume.getMajorResearchDirection())
            .set("selfEvaluation", cvResume.getSelfEvaluation())
            .set("otherSituations", cvResume.getOtherSituations())
            .set("national", info.getR2())
            .set("maritalStatus", info.getMaritalStatus() == null ? "无" : maritalStatus[info.getMaritalStatus()])
            .set("foreignLanguage", info.getForeignLanguage())
            .set("partyTime", DateUtil.format(info.getPartyTime(), "yyyy.MM.dd"))
            .set("computerSkill", info.getComputerSkill());

        //期望职位
        List<Dict> jobIntension = Lists.newArrayList();
        List<CvWorkIntention> workIntentions = cvWorkIntentionService.lambdaQuery()
            .eq(CvWorkIntention::getDelFlag, false)
            .eq(CvWorkIntention::getResumeId, cvResume.getId())
            .orderByDesc(CvWorkIntention::getCreateTime)
            .list();
        for (CvWorkIntention workIntention : workIntentions) {
            String[] nature = workIntention.getWorkNature().split(",");
            String[] city = workIntention.getCityId().split(",");
            String[] industry = workIntention.getWorkIndustry().split(",");
            String hopeType = StrUtil.equals(workIntention.getWorkType(), "0") ?
                "全职" : StrUtil.equals(workIntention.getWorkType(), "1") ?
                "兼职" : "实习";
            String hopeCity = "";
            try {
                StringBuilder hopeCitySb = new StringBuilder();
                for (String c : city) {
                    hopeCitySb.append(transNameUtil.getTransName("sys_area", c, "id", "name")).append("/");
                }
                hopeCity = hopeCitySb.toString();
                hopeCity = hopeCity.substring(0, hopeCity.length() - 1);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Dict intention = Dict.create()
                .set("hopeJob", transNameUtil.getTransName("recruitment_position", nature[nature.length - 1], "id", "name"))
                .set("hopeCity", hopeCity)
                .set("hopeMoney", StrUtil.format("{}-{}", workIntention.getMinMoney(), workIntention.getMaxMoney()))
                .set("hopeIndustry", transNameUtil.getTransName("sys_industry", industry[industry.length - 1], "id", "name"))
                .set("hopeType", hopeType);
            jobIntension.add(intention);
        }
        dict.set("jobIntension", jobIntension);
        //工作/实习经历
        List<Dict> workInfos = Lists.newArrayList();
        List<CvUserWorkInfo> userWorkInfos = cvUserWorkInfoService.lambdaQuery()
            .eq(CvUserWorkInfo::getDelFlag, false)
            .orderByDesc(CvUserWorkInfo::getWorkEndTime)
            .eq(CvUserWorkInfo::getResumeId, cvResume.getId())
            .orderByDesc(CvUserWorkInfo::getWorkStartTime)
            .list();
        for (CvUserWorkInfo userWorkInfo : userWorkInfos) {
//            String time = StrUtil.format("{}-{}", new DateTime(userWorkInfo.getWorkStartTime()).toString(FORMAT), new DateTime(userWorkInfo.getWorkEndTime()).toString(FORMAT));
            String time = StrUtil.format("{}-{}", new DateTime(userWorkInfo.getWorkStartTime()).toString(FORMAT),userWorkInfo.getWorkEndTime().equals(CommonConstant.TO_THIS_DAY)? CommonConstant.TO_THIS_DAY : new DateTime(DateUtils.str2Date(userWorkInfo.getWorkEndTime(), DateUtils.date_sdf.get())).toString(FORMAT));
            String[] job = userWorkInfo.getPositionName().split(",");
            String jId = ArrayUtil.get(job, -1);
            String jobName=null;
            if(StringUtils.equals(jId, CommonConstant.OTHER_POSITION)&&StringUtils.isNotBlank(userWorkInfo.getOtherPosition())){
                jobName = userWorkInfo.getOtherPosition();
            }
            else{
                jobName = transNameUtil.getTransName("recruitment_position", jId, "id", "name");//职位
            }
            Dict workInfo = Dict.create()
                .set("time", time)
                .set("companyName", userWorkInfo.getCompanyName())
                .set("jobName", jobName)
                .set("salary", userWorkInfo.getSalary())
                .set("jobDesc", userWorkInfo.getWorkContent());
            workInfos.add(workInfo);
        }
        dict.set("workInfos", workInfos);
        //教育经历
        List<Dict> education = Lists.newArrayList();
        List<CvUserEduInfo> userEduInfos = cvUserEduInfoService.lambdaQuery()
            .eq(CvUserEduInfo::getDelFlag, false)
            .eq(CvUserEduInfo::getResumeId, cvResume.getId())
            .isNotNull(CvUserEduInfo::getEduLevel)
            .orderByDesc(CvUserEduInfo::getStartEduTime)
            .list();
        for (CvUserEduInfo userEduInfo : userEduInfos) {
            Integer lv = userEduInfo.getEduLevel();
            userEduInfo.setEduLevel(lv == null ? level.length - 1 : lv);
            String time = StrUtil.format("{}-{}", new DateTime(userEduInfo.getStartEduTime()).toString(FORMAT), new DateTime(userEduInfo.getEndEduTime()).toString(FORMAT));
            Dict edu = Dict.create()
                .set("time", time)
                .set("schoolName", userEduInfo.getSchoolName())
                .set("specialty", userEduInfo.getMajor())
                .set("level", eduLabelUtil.getEduLevel(userEduInfo.getEduLevel()));
            String degreeText = eduLabelUtil.geDegree(userEduInfo.getR1(), lanType);
            // 学位
            edu.set("degree", degreeText);
            String fullFlag = userEduInfo.getR2();
            String fullFlagText = "";
            if (StringUtils.isNotBlank(fullFlag)) {
                if (lanType == 0) {
                    fullFlagText = StrUtil.equals(fullFlag, "1") ? "是" : "不是";
                } else {
                    fullFlagText = StrUtil.equals(fullFlag, "1") ? "YES" : "NO";
                }

            }
            // 是否全日制
            edu.set("fullFlag", fullFlagText);

            education.add(edu);
        }
        userEduInfos.sort(Comparator.comparingInt(CvUserEduInfo::getEduLevel).reversed());
        if (CollUtil.isEmpty(userEduInfos)) {
            dict.set("heightEducation", level[level.length - 1]);
        } else {
            dict.set("heightEducation", level[userEduInfos.get(0).getEduLevel()]);
        }
        dict.set("education", education);
        //项目经历
        List<Dict> projects = Lists.newArrayList();
        List<CvProjectInfo> projectInfos = cvProjectInfoService.lambdaQuery()
            .eq(CvProjectInfo::getDelFlag, false)
            .eq(CvProjectInfo::getResumeId, cvResume.getId())
            .orderByDesc(CvProjectInfo::getStartTime)
            .list();
        for (CvProjectInfo projectInfo : projectInfos) {
            String time = StrUtil.format("{}-{}", new DateTime(projectInfo.getStartTime()).toString(FORMAT), new DateTime(projectInfo.getEndTime()).toString(FORMAT));
            Dict project = Dict.create()
                .set("time", time)
                .set("projectName", projectInfo.getProjectName())
                .set("r1", projectInfo.getR1())//项目职务
                .set("r2", projectInfo.getR2())//所在公司
                .set("r3", StrUtil.isBlank(projectInfo.getR3()) ? "/" : projectInfo.getR3()) //项目职责
                .set("r4", StrUtil.isBlank(projectInfo.getR4()) ? "/" : projectInfo.getR4()) //项目职责
                .set("intro", projectInfo.getProjectDescribe());
            projects.add(project);
        }
        dict.set("projects", projects);
        //培训经历
        List<Dict> trainInfos = Lists.newArrayList();
        List<CvTrain> trainList = cvTrainService.lambdaQuery()
            .eq(CvTrain::getDelFlag, false)
            .eq(CvTrain::getResumeId, cvResume.getId())
            .orderByDesc(CvTrain::getEndTime)
            .list();
        for (CvTrain train : trainList) {
            String time = StrUtil.format("{}-{}", new DateTime(train.getStartTime()).toString(FORMAT), new DateTime(train.getEndTime()).toString(FORMAT));
            Dict trainInfo = Dict.create()
                .set("time", time)
                .set("institutionName", train.getMechanismName())
                .set("curriculum", train.getCurriculum());
            trainInfos.add(trainInfo);
        }
        dict.set("trainInfos", trainInfos);
        //语言水平
        List<Dict> languages = Lists.newArrayList();
        List<CvLanguageLevel> languageLevels = cvLanguageLevelService.lambdaQuery()
            .eq(CvLanguageLevel::getDelFlag, false)
            .eq(CvLanguageLevel::getResumeId, cvResume.getId())
            .list();
        for (CvLanguageLevel languageLevel : languageLevels) {
            Dict language = Dict.create()
                .set("name", languageLevel.getType())
                .set("readLevel", languageLevel.getReadingLevel())
                .set("oralLevel", languageLevel.getOralLanguageLevel());
            languages.add(language);
        }
        dict.set("languages", languages);
        //职业特长与技能（专业技能）
        List<Dict> professionalSkill = Lists.newArrayList();
        List<CvSkills> skillsInfos = cvSkillsService.lambdaQuery()
            .eq(CvSkills::getDelFlag, false)
            .eq(CvSkills::getResumeId, cvResume.getId())
            .orderByDesc(CvSkills::getTime)
            .list();
        for (CvSkills skillsInfo : skillsInfos) {
            Dict skills = Dict.create()
                .set("name", skillsInfo.getName())
                .set("level", skillsInfo.getLevel())
                .set("duration", skillsInfo.getTime());
            professionalSkill.add(skills);
        }
        dict.set("professionalSkill", professionalSkill);
        //资质证书
        List<Dict> certificate = Lists.newArrayList();
        List<CvCertificate> certificateInfos = cvCertificateService.lambdaQuery()
            .eq(CvCertificate::getDelFlag, false)
            .eq(CvCertificate::getResumeId, cvResume.getId())
            .orderByDesc(CvCertificate::getTime)
            .list();
        for (CvCertificate certificateInfo : certificateInfos) {
            Dict skills = Dict.create()
                .set("time", new DateTime(certificateInfo.getTime()).toString(FORMAT))
                .set("licenseIssuingUnit", certificateInfo.getLicenseIssuingUnit())
                .set("name", certificateInfo.getName());
            certificate.add(skills);
        }
        dict.set("certificate", certificate);

        // 家庭成员

        List<CvFamilyMember> familyMembers = cvFamilyMemberService.lambdaQuery().eq(CvFamilyMember::getResumeId, cvResume.getId())
            .eq(CvFamilyMember::getDelFlag, 0)
            .orderByDesc(CvFamilyMember::getCreateTime).list();
        dict.set("familyMembers", familyMembers);

        //附件
        List<File> files = new ArrayList<>();
        if (org.apache.commons.lang.StringUtils.isNotBlank(cvResume.getEnclosureId())) {
            String[] strings = cvResume.getEnclosureId().split(",");
            files = fileService.lambdaQuery().in(File::getId, strings).list();
        }
        dict.set("attachment", files);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        String template = lanType == 0 ? "resume_template.ftl" : "resume_template_en.ftl";
        //校招
        boolean school = cvResume.getResumeType() == 2;
        if (school) {
            template = lanType == 0 ? "resume_school_zh.ftl" : "resume_school_en.ftl";
        }
        TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("resume/html/", TemplateConfig.ResourceMode.CLASSPATH));
        engine.getTemplate(template).render(dict, byteArrayOutputStream);
        String path = "/private/resume/" + cn.hutool.core.date.DateUtil.format(cvResume.getCreateTime(), "yyyy/MM/");
        path = sysBaseAPI.uploadToLocal(byteArrayOutputStream.toByteArray(), path, resumeHtmlName, false).toString();
        if (cvResume != null && lanType != null && StringUtils.isNotBlank(path)) {
            if (0 == lanType) {
                cvResume.setPdfPath(path);
                cvResumeService.updateById(cvResume);
            } else if (1 == lanType) {
                cvResume.setPdfPathEn(path);
                cvResumeService.updateById(cvResume);
            }
        }
        return path;
    }

}
